﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    public float speed = 110f;
    public BaseTank tank;
    private GameObject skin;
    private Rigidbody rigidbody;

    public void Init()
    {
        GameObject skinRes = ResManager.LoadPrefab("bulletPrefab");
        skin = Instantiate(skinRes);
        skin.transform.parent = this.transform;
        skin.transform.localPosition=Vector3.zero;
        skin.transform.localEulerAngles=Vector3.zero;

        rigidbody = gameObject.AddComponent<Rigidbody>();
        rigidbody.useGravity = false;
    }

    private void Update()
    {
        transform.position += transform.forward * speed * Time.deltaTime;
    }

    private void OnCollisionEnter(Collision collision)
    {
        GameObject collObj = collision.gameObject;
        BaseTank hitTank = collObj.GetComponent<BaseTank>();

        if (hitTank==tank)
        {
            return;
        }
        if(hitTank != null){
            SendMsgHit(tank,hitTank);
        }

        GameObject explode = ResManager.LoadPrefab("explosion");
        Instantiate(explode, transform.position, transform.rotation);
        
        Destroy(gameObject);
    }

    void SendMsgHit(BaseTank tank, BaseTank hitTank)
    {
        if (hitTank==null||tank==null)
        {
            return;
        }

        if (tank.id!=GameMain.id)
        {
            return;
        }

        MsgHit msg = new MsgHit();
        msg.targetId = hitTank.id;
        msg.id = tank.id;
        msg.x = transform.position.x;
        msg.y = transform.position.y;
        msg.z = transform.position.z;
        NetManager.Send(msg);
    }
    
}
